<template>
    <el-dialog
        v-model="dialogVisible"
        :title="type === 'add' ? '新增角色' : '编辑角色'"
        width="500px"
        @close="handleClose"
    >
        <el-form
            ref="formRef"
            :model="roleForm"
            :rules="rules"
            label-width="100px"
        >
            <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="roleForm.roleName" placeholder="请输入角色名称" />
            </el-form-item>
            <el-form-item label="角色描述" prop="roleDescribe">
                <el-input 
                    v-model="roleForm.roleDescribe" 
                    type="textarea" 
                    :rows="3"
                    placeholder="请输入角色描述" 
                />
            </el-form-item>
            <el-form-item label="角色状态" prop="roleStatus">
                <el-radio-group v-model="roleForm.roleStatus">
                    <el-radio :value="1">启用</el-radio>
                    <el-radio :value="2">禁用</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="权限配置" prop="rolePermissions">
                <div class="permission-select">
                    <div class="selected-text" v-if="selectedCount > 0">
                        已选择 {{ selectedCount }} 个权限
                    </div>
                    <el-button @click="showPermissionDialog">选择权限</el-button>
                </div>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="handleClose">取消</el-button>
                <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
                    确定
                </el-button>
            </span>
        </template>
    </el-dialog>

    <permission-tree
        v-model="permissionDialogVisible"
        :permission-list="permissionList"
        :checked-permissions="roleForm.rolePermissions"
        @change="handlePermissionChange"
    />
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { Create, Update, type UserRole } from '@/apis/role'
import type { UserPermission } from '@/apis/permission'
import PermissionTree from './PermissionTree.vue'

const props = defineProps<{
    modelValue: boolean
    type: 'add' | 'edit'
    roleData?: UserRole
    permissionList: UserPermission[]
}>()

const emit = defineEmits<{
    (e: 'update:modelValue', value: boolean): void
    (e: 'success'): void
}>()

// 状态变量
const dialogVisible = ref(props.modelValue)
const permissionDialogVisible = ref(false)
const submitLoading = ref(false)
const formRef = ref<FormInstance>()

// 表单数据
const roleForm = ref<UserRole>({
    roleName: '',
    roleDescribe: '',
    roleStatus: 1,
    rolePermissions: '',
    updateTime: '',
    uUID: ''
})

// 已选择的权限数量
const selectedCount = computed(() => {
    if (!roleForm.value.rolePermissions) return 0
    return roleForm.value.rolePermissions.split(',').length
})

// 监听对话框显示状态
watch(() => props.modelValue, (val) => {
    dialogVisible.value = val
})

watch(() => dialogVisible.value, (val) => {
    emit('update:modelValue', val)
})

// 监听编辑数据
watch(() => props.roleData, (val) => {
    if (val) {
        roleForm.value = { ...val }
    } else {
        roleForm.value = {
            roleName: '',
            roleDescribe: '',
            roleStatus: 1,
            rolePermissions: '',
            updateTime: '',
            uUID: ''
        }
    }
}, { immediate: true })

// 显示权限选择对话框
const showPermissionDialog = () => {
    permissionDialogVisible.value = true
}

// 处理权限选择变化
const handlePermissionChange = (value: string) => {
    roleForm.value.rolePermissions = value
}

// 表单校验规则
const rules = {
    roleName: [
        { required: true, message: '请输入角色名称', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
    ],
    roleStatus: [
        { required: true, message: '请选择角色状态', trigger: 'change' }
    ]
}

// 提交表单
const handleSubmit = async () => {
    if (!formRef.value) return
    
    await formRef.value.validate(async (valid, fields) => {
        if (!valid) return
        
        submitLoading.value = true
        try {
            if (props.type === 'add') {
                await Create(roleForm.value)
                ElMessage.success('新增成功')
            } else {
                await Update(roleForm.value)
                ElMessage.success('更新成功')
            }
            handleClose()
            emit('success')
        } catch (error) {
            console.error('操作失败:', error)
            ElMessage.error('操作失败')
        } finally {
            submitLoading.value = false
        }
    })
}

// 关闭对话框
const handleClose = () => {
    dialogVisible.value = false
    formRef.value?.resetFields()
    roleForm.value = {
        roleName: '',
        roleDescribe: '',
        roleStatus: 1,
        rolePermissions: '',
        updateTime: '',
        uUID: ''
    }
}
</script>

<style scoped lang="scss">
.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 8px;
}

.permission-select {
    display: flex;
    align-items: center;
    gap: 8px;

    .selected-text {
        color: var(--el-text-color-secondary);
    }
}
</style> 